package com.feng.config;

import org.springframework.security.crypto.password.PasswordEncoder;
import sun.misc.BASE64Encoder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SpringSecurity 的 PasswordEncoder 自定义 使用md5
 * @author: 丰
 * @date: 2023/1/9 12:19
 */
public class Md5PasswordEncoderConfig implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        MessageDigest md5 = null;
        if (rawPassword == null){
            return "";
        }
        String password = rawPassword.toString();
        try {
            md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(md5.digest(password.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 123456
        return "4QrcOUm6Wau+VuBX8g+IPg==";
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        // 前端输入的密码进行加密
        String encode = encode(rawPassword);
        // 与数据库读出来加密过后的密码进行比较
        return encode.equals(encodedPassword);
    }
}
